<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use Hyperf\Server\ServerFactory;

class IndexController extends AbstractController
{
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        $server = $this->container->get(ServerFactory::class)->getServer()->getServer();
        $fdList = $server->connections;
        foreach ($fdList as $key => $fd) {
            if (!empty($fd)) {
                // $fd 非websocket时有警告
                //通过使用$server->connection_info($fd)获取连接信息，返回的数组中有一项为 websocket_status，
                //根据此状态可以判断是否为WebSocket客户端。
                //WEBSOCKET_STATUS_CONNECTION = 1，连接进入等待握手
                //WEBSOCKET_STATUS_HANDSHAKE = 2，正在握手
                //WEBSOCKET_STATUS_FRAME = 3，已握手成功等待浏览器发送数据帧
                $server->push((int)$fd, "from IndexController User：{$user}");
            }
        }

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }
}
